<?php
/**
 * 员工 Logic
 */

namespace app\common\logic;

use app\common\model\CompanyStructure;
use app\v1_0\controller\company\Structure;
use phpService\PdfService;
use Think\Exception;

class StaffLogic {


    static function getStructureIds($name,$company_profile){
        $item = model('CompanyStructure')
            ->field('id,p_id')
            ->where(['com_id'=>$company_profile->id,'name' =>['like',  $name. '%']])
            ->find();
        if(empty($item)){
            return '';
        }
        if($item->p_id != 0)
        {
            $ids =self::getIds($item->p_id);
            array_push($ids,$item->id);
            sort($ids);
           return implode(',',$ids);
        }else{
            return $item->id;
        }
    }

    static function getIds($pid,$ids=[]){

        if($pid == 0){
            $where = ['p_id'=>$pid];
        }else{
           $where = ['id'=>$pid];
        }
        $structure = model('CompanyStructure')
            ->field('id,p_id')
            ->where($where)
            ->find();
        $pid = $structure->p_id == 0 ? null :$structure->p_id;
        $ids[] = $structure->id;
        if($pid === null){
            return $ids;
        } else{
            return self::getIds($pid,$ids);
        }
    }
    /**
     * 简历导入
     */
    static function import($dataList, $company_profile) {

        \think\Db::startTrans();
        try {
            $list= [];
            $Staff = model('CompanyStaffManage')->where(['mobile' => ['in',array_column($dataList,'mobile')]])->column('id','mobile');

            foreach ($dataList as $item) {
//                $item['entry_time'] || $item['entry_time'] = time();
                $data = [
                    'com_id' => $company_profile->id,
                    'name' => trim($item['name']),
                    'gender' => $item['gender'],
                    'postname' => $item['postname'],
                    'mobile' => $item['mobile'],
                    'mailbox' => $item['mailbox'],
                    'job_nature' => $item['job_nature'],
                    'entry_status' => $item['entry_status'],
                    'entry_time' => date('Y-m-d', $item['entry_time']?strtotime($item['entry_time']):time()),
                ];
                if(stripos($data['entry_status'],'调岗') !== false) {
                    $data['transfer'] = '是';
                }

                $company =trim($item['company']);
                $department =trim($item['department']);
                $department_1 =trim($item['department_1']);
                $data ['coms_id'] = model('CompanyStructure')
                    ->where(['p_id' =>0,'com_id'=>$company_profile->id,'type'=>1])
                    ->value('id');
                if($company){
                    $coms_d_id_1 = model('CompanyStructure')
                        ->where(['com_id'=>$company_profile->id,'type'=>1])->whereRaw('name REGEXP "'.$company.'"')
                        ->value('id');
                }else{
                    $coms_d_id_1 = 0;
                }
                $coms_d_id_2 = '';
                if(empty($department)){

                }else{
                    $company_structure = model('CompanyStructure')
                        ->where(['com_id'=>$company_profile->id,'type'=>2])->when($coms_d_id_1,function($q)use($coms_d_id_1){
                            $q->where('p_id',$coms_d_id_1);
                        })->where('name REGEXP "'.$department.'"')
                        ->field('id,p_id')->find();
                    if($company_structure){
                        $coms_d_id_2 = $company_structure['id'];
                        !$coms_d_id_1 && $coms_d_id_2 && $coms_d_id_1 = $company_structure['p_id'];
                    }
                }

                $coms_d_id_3 = '';
                if(empty($department_1)){

                }else{
                    $company_structure = model('CompanyStructure')
                        ->where(['com_id'=>$company_profile->id,'type'=>2])->when($coms_d_id_2,function($q)use($coms_d_id_2){
                            $q->where('p_id',$coms_d_id_2);
                        })->where('name REGEXP "'.$department_1.'"')
                        ->field('id,p_id')->find();
                    if($company_structure){
                        if(!$coms_d_id_2){
                            $coms_d_id_2 = $company_structure['p_id'];
                        }
                        if(!$coms_d_id_1){
                            $coms_d_id_1 = CompanyStructure::where(['com_id'=>$company_profile->id,'type'=>1,'id'=>$coms_d_id_2])->value('p_id');
                        }
                    }
                }
                $data['coms_d_id'] = $coms_d_id_1 ? $coms_d_id_1.($coms_d_id_2 ? ',' . $coms_d_id_2 . ($coms_d_id_3 ? ',' . $coms_d_id_3 : '') : '') : '';

                if (!empty($Staff[$item['mobile']])) {
                    $data['id']=$Staff[$item['mobile']];
                    $update[] = $data;
                }else{
                    $list [] =$data;
                }
               unset($data);
            }

            !empty($update) && model('CompanyStaffManage')->saveAll($update);
            if (!empty($list)) {
                model('CompanyStaffManage')->saveAll($list);
                foreach ($list as $item){
                    //新增数据 更新企业架构当前人员
                    $coms_id = explode(',',(string)$item['coms_id']);
                    $coms_d_id = explode(',',(string)$item['coms_d_id']);
                    $pid = end($coms_d_id)?end($coms_d_id):end($coms_id);
                    (new Structure())->makeCompanyCurrentNum($pid,1);
                }
            }
            \think\Db::commit();
            return true;
        } catch (\Exception $e) {
            \think\Db::rollBack();
            $return = [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'data' => [$e->getMessage(),$e->getLine(),$e->getFile()]
            ];
            exit(json_encode($return, JSON_UNESCAPED_UNICODE));
        }

    }
    static function importDemo($dataList, $company_profile) {

        \think\Db::startTrans();
        try {
            $list= [];
            foreach ($dataList as $item) {

                $data = [
                    'com_id' => $company_profile->id,
                    'name' => trim($item['name']),
                    'gender' => $item['gender'],
                    'postname' => $item['postname'],
                    'mobile' => $item['mobile'],
                    'mailbox' => $item['mailbox'],
                    'job_nature' => $item['job_nature'],
                    'entry_status' => $item['entry_status'],
                    'entry_time' => date('Y-m-d', strtotime($item['entry_time'])),
                ];

                $company =trim($item['company']);
                $department =trim($item['department']);
                $department_1 =trim($item['department_1']);
                if(empty($company)){
                    $data ['coms_id'] = model('CompanyStructure')
                        ->where(['p_id' =>0,'com_id'=>$company_profile->id,'type'=>1])
                        ->value('id');
                }else{
                    $data ['coms_id'] = self::getStructureIds($company,$company_profile);
                }
                if(empty($department)){
                    $data ['coms_d_id'] = '';
                }else{
                    $data ['coms_d_id'] = self::getStructureIds($department,$company_profile);
                }

                $Staff = model('CompanyStaffManage')->where(['mobile' => $data['mobile'], 'name' => $data['name']])->find();

                if (!empty($Staff)) {
                    //TODO:需要过滤
                    //*********
                    $data['id']=$Staff->id;

                }
                $list [] =$data;
               unset($data);
            }
            if (!empty($list)) {
                model('CompanyStaffManage')->saveAll($list);

                foreach ($list as $item){
                    if(!isset($item['id'])){
                        //新增数据 更新企业架构当前人员
                        $coms_id = explode(',',(string)$item['coms_id']);
                        $coms_d_id = explode(',',(string)$item['coms_d_id']);
                        $pid = end($coms_d_id)?end($coms_d_id):end($coms_id);
                        (new Structure())->makeCompanyCurrentNum($pid,1);
                    }
                }
            }
            \think\Db::commit();
            return true;
        } catch (\Exception $e) {
            \think\Db::rollBack();
            $return = [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'data' => []
            ];
            exit(json_encode($return, JSON_UNESCAPED_UNICODE));
        }

    }


}